package spms.front.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import io.swagger.annotations.Api;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import spms.data.SpmsDataRemoteApi;
import spms.data.entity.Menu;
import spms.util.Page;

import javax.annotation.Resource;

@Api(tags = "Menu")
@Controller
public class MenuController {
    private final Logger logger = LoggerFactory.getLogger(getClass());


    @Resource
    SpmsDataRemoteApi spmsDataRemoteApi;

    /**
     * AJAX 加载左侧菜单
     **/
    @PostMapping("getMenuList")
    @ResponseBody
    public Object getMenuList() {
        return spmsDataRemoteApi.findMenuAll();
    }

    /**
     * 跳转菜单列表页面
     */
    @GetMapping("/menuList")
    public Object menuList(@RequestParam(defaultValue = "0") Integer pageNum, @RequestParam(defaultValue = "10") Integer pageSize, Model model) {
        getMenuList(pageNum, pageSize, model);
        return "menuList";
    }

    /**
     * 通过父菜单获取子菜单列表
     *
     * @param pageNum  页码
     * @param pageSize 页面大小
     */
    @PostMapping("/menuList")
    public Object getMenuList(@RequestParam(defaultValue = "0") Integer pageNum, @RequestParam(defaultValue = "10") Integer pageSize, Model model) {

        Page<Menu> page = spmsDataRemoteApi.findMenuPage(pageNum, pageSize);

        model.addAttribute("page", page);
        return "menuList::menuList";
    }

    public void sortMenu(JSONArray jsonArray) {
        jsonArray.sort((v1, v2) -> {
            JSONObject job1 = (JSONObject) v1;
            JSONObject job2 = (JSONObject) v2;
            if (job1.containsKey("submenu") && !job1.getJSONArray("submenu").isEmpty()) {
                JSONArray ja = job1.getJSONArray("submenu");
                sortMenu(ja);
            }
            return job1.getInteger("order").compareTo(job2.getInteger("order"));
        });

    }
}
